var IndexStat = {
    layerIndex: -1,
};
$(function () {
    $.parser.parse(); // 解析整个页面
    var lastMonths = getLastMonthStartDate().substring(0, 7);//YYYY-MM-DD
    var lastYearMonth = getOneYearStartDate().substring(0, 7);
    $("#startDate").val(lastYearMonth);
    $("#endDate").val(lastMonths);
    laydate.render({
        elem : '#dateRange',
        type : 'month',
        theme: '#afcede',
        range : true,
        value: lastYearMonth+' - '+lastMonths,
        done: function(value, start, end){
            var startMonth = start.month<10?"0"+start.month:start.month;
            var endMonth = end.month<10?"0"+end.month:end.month;
            var startDate = start.year+"-"+startMonth;
            var endDate = end.year+"-"+endMonth;
            $("#startDate").val(startDate);
            $("#endDate").val(endDate);
        }
    });
    $HUI.combobox('#Hospital',
        {
            data:$.parseJSON($("#officeMap").val()),
            valueField:'value',
            textField:'text',
            onSelect:IndexStat.officeChange,
            defaultFilter: 6,
            onLoadSuccess: function () { //加载完成后,val[0]写死设置选中第一项
                var val = $(this).combobox("getData");
                if(val.length==2){//如果就一个院区 加上全部=2
                    $(this).combobox("setValue", val[1].value);
                    IndexStat.officeChange(val[1]);
                    $("#oneOffice").val("yes");
                }else{
                    $(this).combobox("setValue", "");
                    $("#oneOffice").val("no");
                }
            }
        } )
    $HUI.combobox('#LocDic',
        {
            data:$.parseJSON($("#departMap").val()),
            valueField:'value',
            textField:'text',
            defaultFilter: 6
            //目前主任医师和科室无关联
            //onSelect:IndexStat.LocChange
        })
    $HUI.combobox('#QCDic',
        {
            data:$.parseJSON($("#entityMap").val()),
            valueField:'value',
            textField:'text',
            defaultFilter: 6,
            onLoadSuccess: function () { //加载完成后,val[0]写死设置选中第一项
                var val = $(this).combobox("getData");
                $(this).combobox("setValue", val[1].value);
            }
        })
    $("#entityDesc").panel({title:"单病种指标统计表格数据"});
    //费用,住院日
    IndexStat.drawSysSumChart();
    //绘制标统计表格
    IndexStat.drawTable();
});
$('#search').on('click', function () {
    IndexStat.drawSysSumChart();
    IndexStat.drawTable();
});

IndexStat.officeChange = function(that){
    var ajax = new $ax("/sds/common/deptListByHospId", function(data){
        $('#LocDic').combobox({
            data:data,
            valueField:'value',
            textField:'text',
            defaultFilter: 6,
            onLoadSuccess: function () { //加载完成后,val[0]写死设置选中第一项
                $(this).combobox("setValue", "");
            }
        });
    },function(data){
        layer.msg("查询失败!" + data.responseJSON.message + "!",{icon: 2});
    });
    ajax.set({"hospID":that.value,"id":"depart"});
    ajax.start();
}

IndexStat.drawTable = function(){
    var columns = [],
        initColumns = [],//公共固定列
        itemColumns = []; //动态因子列
    initColumns = [
        {title: '出院时间', field: 'dishDate', align: 'left', valign: 'middle', sortable: true,width:80,rowspan: 2,
            footerFormatter:function(value){
                return "总计";
            }
        },
        {title: '出院人数', field: 'num', align: 'left', valign: 'middle', sortable: true,width:80,rowspan: 2,
            /*formatter:function(value,row,index){
                console.log(row)
                return "<a onclick='IndexStat.showIndexDetail(\""+row.ids+"\")'>"+value+"</a>";
            },*/
            footerFormatter:function(value){
                return IndexStat.sumFieldValue(value,"num");
            }
        }
    ];

    var params = {};
    var ajax = new $ax("/api/selectIndexTableData", function (data) {
        var dataA = data.tableColumnAs;
        var dataB = data.tableColumnBs;
        var dataTable = data.tableDates;
        //查询病种对应一级表头
        for (var i = 0; i < dataA.length; i++){
            initColumns.push (
                {
                    field: "",
                    title: dataA[i].title ,
                    width: dataA[i].colspan * 150,
                    align: "center",
                    halign: "center",
                    colspan: dataA[i].colspan
                }
            );
        }
        //查询病种对应二级表头
        for (var i = 0; i < dataB.length; i++){
            let fieldNum = dataB[i].fieldNum;
            let fieldName = dataB[i].field;
            if (dataB[i].parentId==0){
                initColumns.push (
                    {
                        field: dataB[i].field,
                        title: dataB[i].title ,
                        width: 150,
                        align: "left",
                        valign: 'middle',
                        rowspan: 2,
                        footerFormatter:function(value){
                            return IndexStat.sumFieldValue(value,fieldName);
                        }
                    }
                );
            }else {
                itemColumns.push (
                    {
                        field: dataB[i].field,
                        title: dataB[i].title ,
                        width: 150,
                        align: "left",
                        valign: 'middle',
                        footerFormatter:function(value){
                            return IndexStat.sumFieldValue(value,fieldName);
                        }
                    }
                );
            }
        }
        //住院日期不参与计算，直接取值，避免造成数据不一致
        initColumns.push (
            {
                field: "averageDays",
                title: "住院天数" ,
                width: 150,
                align: "left",
                valign: "middle",
                rowspan: 2,
                footerFormatter:function(value){
                    return IndexStat.sumFieldValue(value,"averageDays");
                }
            }
        );
        columns.push(initColumns, itemColumns); //合并表格内容
        this.$table =
            $('#indexStatTable').bootstrapTable('destroy').bootstrapTable({
                data:dataTable,
                striped: false,//是否显示行间隔色
                pagination: false,//是否显示分页
                showFooter: true,
                //paginationLoop: false,
                //pageSize : 5,//用于设置每页初始显示的条数
                //pageList :[4],
                //sidePagination: 'server',//设置在哪进行分页，默认”client”，可选”server”,返回数据模板不同
                sortName: "patientNum",
                sortOrder: 'desc',// desc  asc
                maintainSelected: true,//设为true 为选中的状态
                cache: false,
                search: false, //搜索框
                columns: columns,
                onPostHeader: function(){  //当<thead></thead>中的内容被加载完后或者在你所用的DOM中有定义则被触发
                    // $(".th-inner").css("font-weight","700");//表头字体加粗
                    $("#indexStatTable > tbody td").each(function(index){//鼠标悬浮 显示表格数据
                        $(this).attr("title",$(this).text());
                    });
                },
                onPostBody:function (dataTable) {
                    merge_footer();
                },
            });
    }, function (data) {
    });
    params.aHospID = Common_GetValue('Hospital');
    params.aQCEntity = Common_GetText('QCDic');
    params.qcEntity = Common_GetValue('QCDic');
    params.aLocDesc = replaceValue(Common_GetText('LocDic'));
    params.aLocID  = replaceValue(Common_GetValue('LocDic'));
    params.startDate = $('#startDate').val();
    params.endDate = $('#endDate').val();
    ajax.set(params);
    ajax.start();
};

IndexStat.drawSysSumChart = function(){
    //疾病系统费用展现
    var params = {};
    var ajax = new $ax("/api/selectSysSumChart", function (data) {
        var xdata = []
        var ydata = []
        var dataArr = data.res
        var datalen = dataArr.length
        for (var i = 0; i < datalen; i++) {
            var row = dataArr[i]
            xdata.push(row.date);
            ydata.push(row.averageCosts);
        }
        var myChart = echarts.init(document.getElementById('CostInfo'));
        // 指定图表的配置项和数据
        var option = {
            title: {
                text: '疾病费用'
            },
            tooltip: {},
            legend: {},
            xAxis: {
                data: xdata,
                axisLine: {
                    lineStyle: {

                    }
                }
            },
            yAxis: {},
            series: [
                {
                    name: '平均费用',
                    type: 'line',
                    smooth: true,
                    showAllSymbol: true,
                    symbol: 'emptyCircle',
                    symbolSize: 15,
                    data: ydata,
                    markLine: {
                        data: [{ type: 'average', name: '月均费用' }]
                    }
                },

            ]
        };
        myChart.setOption(option);

        //疾病系统住院日展现
        var xdata = []
        var ydata = []
        for (var i = 0; i < datalen; i++) {
            var row = dataArr[i]
            xdata.push(row.date);
            ydata.push(row.averageDays);
        }
        var myChart = echarts.init(document.getElementById('IndaysInfo'));
        // 指定图表的配置项和数据
        var option = {
            title: {
                text: '住院天数'
            },
            tooltip: {},
            legend: {},
            xAxis: {
                data: xdata,
                axisLine: {
                    lineStyle: {

                    }
                }
            },
            yAxis: {},
            series: [
                {
                    name: '平均住院天数',
                    type: 'line',
                    smooth: true,
                    showAllSymbol: true,
                    symbol: 'emptyCircle',
                    symbolSize: 15,
                    data: ydata,
                    markLine: {
                        data: [{ type: 'average', name: '月均天数' }]
                    }
                },

            ]
        };
        myChart.setOption(option);
    }, function (data){
    });
    params.aHospID = Common_GetValue('Hospital');
    params.aQCEntity = Common_GetText('QCDic');
    params.aLocDesc = replaceValue(Common_GetText('LocDic'));
    params.aLocID  = replaceValue(Common_GetValue('LocDic'));
    params.startDate = $('#startDate').val();
    params.endDate = $('#endDate').val();
    ajax.set(params);
    ajax.start();
}

//取值
function Common_GetText()
{
    var itmValue = '';

    if (typeof(arguments[0]) !== 'string') return '';
    if (arguments[0] == '') return '';

    var $this = $('#'+ arguments[0]);
    if ($this.length < 1) return '';

    var className = $this.attr("class").split(' ')[0];

    if (className == 'textbox') {  //文本框
        itmValue = $this.val();
    }else if (className == 'hisui-numberbox') {  //数字
        itmValue = $this.val();
    }else if (className == 'hisui-datebox') {  //日期
        itmValue = $this.datebox('getValue');
    }else if (className == 'hisui-timespinner') {  //时间框
        itmValue = $this.timespinner('getValue');
    }else if (className == 'hisui-combobox') {  //下拉框
        itmValue = $this.combobox('getText');
    }else if (className == 'hisui-switchbox') {  //开关
        itmValue = $this.switchbox('getValue');
    }else if (className == 'hisui-checkbox') {  // 单个复选框
        itmValue = $this.attr("label");
    }else if (className == 'hisui-radio') {  //单个单选框
        itmValue =$this.attr("label");
    }else if (className == 'hisui-searchbox') {  //查询框框
        itmValue = $this.searchbox('getValue');
    }

    return itmValue;
}

//值为全部替换为空
function replaceValue(text) {
    if ("全部"==text) {
        return ""
    }else {
        return text;
    }
}

//取值
function Common_GetValue()
{
    var itmValue = '';

    if (typeof(arguments[0]) !== 'string') return '';
    if (arguments[0] == '') return '';

    var $this = $('#'+ arguments[0]);
    if ($this.length < 1) return '';

    var className = $this.attr("class").split(' ')[0];

    if (className == 'textbox') {  //文本框
        itmValue = $this.val();
    }else if (className == 'hisui-numberbox') {  //数字
        itmValue = $this.val();
    }else if (className == 'hisui-datebox') {  //日期
        itmValue = $this.datebox('getValue');
    }else if (className == 'hisui-timespinner') {  //时间框
        itmValue = $this.timespinner('getValue');
    }else if (className == 'hisui-combobox') {  //下拉框（多选下拉框没有封装）
        itmValue = $this.combobox('getValue');
    }else if (className == 'hisui-switchbox') {  //开关
        itmValue = $this.switchbox('getValue');
    }else if (className == 'hisui-checkbox') {  // 单个复选框
        itmValue = $this.checkbox('getValue');
    }else if (className == 'hisui-radio') {  //单个单选框
        itmValue = $this.radio('getValue');
    }else if (className == 'hisui-searchbox') {  //查询框框
        itmValue = $this.searchbox('getValue');
    }

    return itmValue;
}

IndexStat.sumFieldValue = function(value,field){
    var disSum = 0;
    var count = 0;
    var tem = 0;
    if (field.indexOf("Fee") >= 0 || field.indexOf("Day") >= 0 || field == "averageDays"){
        for(var i in value){
            count += value[i][field]*100;
            disSum += parseInt(value[i]["num"])*100;
        }
        //disSum = value.length*100;
        count = count/100;
        disSum = disSum/100;

        if (disSum == 0){
            return "";
        }
        var x = value.length
        return (count/x).toFixed(2);
    }else if (field == "num"){
        for(var i in value){
            count += parseInt(value[i][field]);
        }
        return count;
    } else {
        for(var i in value){
            count += value[i][field+"Num"]*1000;
            disSum += parseInt(value[i]["num"])*1000;
        }
        //disSum = value.length*1000;
        count = count/1000;
        disSum = disSum/1000;

        if (disSum == 0){
            return "";
        }

        var pre = (count/disSum * 100).toFixed(2);
        return pre+"%&nbsp;&nbsp;("+count+")";
    }

};

//设置合计列宽度
function merge_footer(){
    //获取table表中footer 并获取到这一行的所有列
    var footer_tbody = $('.fixed-table-footer table tbody');
    var footer_tr = footer_tbody.find('>tr');
    var footer_td = footer_tr.find('>td');
    var footer_td_1 = footer_td.eq(0);
    for(var i=0;i<footer_td.length;i++){
        footer_td.eq(i).hide();//隐藏单元格
        if(i >= 0 && i <= 1){
            footer_td.eq(i).attr('width', "80px").show();//显示单元格并设置列宽
        }else {
            footer_td.eq(i).attr('width', "150px").show();//显示单元格并设置列宽
        }
    }
}

IndexStat.showIndexDetail = function(ids){
    var index = Sys.open_c('指标统计详情数据列表', '/analysis/indexstat/detailList?ids=' + ids + '&qcEntity=' + Common_GetValue('QCDic'), null, function (){
    });
    this.layerIndex = index;
};
/**
 * 导出主页的表格数据
 */
IndexStat.exportTable = function() {
    var qcEntity = Common_GetText('QCDic');
    $("#tableDiv table").tableExport(
        {
            type : 'xlsx',
            escape : 'false',
            fileName : IndexStat.getSystemTime()+qcEntity+'指标统计表'
        },IndexStat.getSystemTime()+qcEntity+'指标统计表'
    )
};

/**
 * 获取当天年月日
 */
IndexStat.getSystemTime = function(){
    function p(s) {
        return s < 10 ? '0' + s: s;
    }
    var date = new Date(); // 获取中国标准时间
    var y = date.getFullYear(); // 年
    var m = date.getMonth()+1; // 月
    var d = date.getDate(); // 日
    var sysTime = y+'-'+p(m)+'-'+p(d);
    return sysTime;
};
